package com.okaixz.client.service.impl;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.okaixz.client.model.domain.PwdTagInfo;
import com.okaixz.client.mapper.PwdTagInfoMapper;
import com.okaixz.client.model.domain.User;
import com.okaixz.client.service.IPwdInfoService;
import com.okaixz.client.service.IPwdTagInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okaixz.client.service.IUserService;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.manager.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdz
 * @since 2025-09-17
 */
@Service
@Slf4j
public class PwdTagInfoServiceImpl extends ServiceImpl<PwdTagInfoMapper, PwdTagInfo> implements IPwdTagInfoService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPwdInfoService pwdInfoService;

    @Override
    public PwdTagInfo addOrUpdate(String name,int type) {
        User user = userService.getTokenUser();
        PwdTagInfo info=null;
        info = lambdaQuery()
                .eq(PwdTagInfo::getUserId, user.getUserId())
                .eq(PwdTagInfo::getName, name)
                .eq(PwdTagInfo::getType, type)
                .one();
        if (info != null) {
            return info;
        }
        info=new PwdTagInfo();
        info.setName(name);
        info.setModifyTime(LocalDateTime.now());
        info.setUserId(user.getUserId());
        info.setType(type);
        boolean b = saveOrUpdate(info);
        if (b) {
//            log.info("tab保存成功：{}",info.toString());
            return info;
        }


        return null;
    }

    @Override
    public Boolean deleteTag(PwdTagInfo pwdTagInfo) {
        User user = userService.getTokenUser();
        String name = pwdTagInfo.getName();
        int type = pwdTagInfo.getType();
        log.info("11111111111======================pwdTagInfo:{}", pwdTagInfo);
        //根据名称和类型删除
        boolean b = lambdaUpdate()
                .eq(PwdTagInfo::getUserId, user.getUserId())
                .eq(PwdTagInfo::getName, name)
                .eq(PwdTagInfo::getType, type)
                .remove();

        //删除密码中的标签
        boolean b1 = pwdInfoService.deleteTag(pwdTagInfo);
        return b&&b1;
    }

    @Override
    public List<PwdTagInfo> uploadAll(List<PwdTagInfo> pwdTagInfoList) {
        if (pwdTagInfoList.size()==0) {
            return null;
        }
        String userId = BaseContext.getUserId();
        if (userId == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        for (PwdTagInfo pwdTagInfo : pwdTagInfoList) {
            pwdTagInfo.setUserId(userId);
        }
        boolean result = saveOrUpdateBatch(pwdTagInfoList);
        if (result) {
            return pwdTagInfoList;
        }
        return null;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<PwdTagInfo> entityList) {
        int batchSize = 1000;
        Assert.notEmpty(entityList, "error: entityList must not be empty");
        Class<?> cls = currentModelClass();
        TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
        String keyProperty = tableInfo.getKeyProperty();
        Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            int i = 0;
            PwdTagInfo oldPwdInfo = null;
            for (PwdTagInfo entity : entityList) {
//                Long id = entity.getId();
//                if (id != null) {
//                    oldPwdInfo=getById(id);
//                }
                oldPwdInfo=lambdaQuery()
                        .eq(PwdTagInfo::getUserId, entity.getUserId())
                        .eq(PwdTagInfo::getName, entity.getName())
                        .eq(PwdTagInfo::getType, entity.getType())
                        .one();

                if (oldPwdInfo==null) {
                    //未查询到信息执行插入
                    entity.setId(null);
                    batchSqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE), entity);
                } else {
                    entity.setId(oldPwdInfo.getId());
                    MapperMethod.ParamMap<PwdTagInfo> param = new MapperMethod.ParamMap<>();
                    param.put(Constants.ENTITY, entity);
                    batchSqlSession.update(sqlStatement(SqlMethod.UPDATE_BY_ID), param);
                }
                // 不知道以后会不会有人说更新失败了还要执行插入 😂😂😂
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
                i++;
            }
            batchSqlSession.flushStatements();
        }
        return true;
    }

    @Override
    public List<PwdTagInfo> downloadAll() {
        String userId = BaseContext.getUserId();
        List<PwdTagInfo> list = lambdaQuery()
                .eq(PwdTagInfo::getUserId, userId)
                .list();
        return list;
    }
}
